package com.lg.cms.shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lg.cms.dto.ShiroUsernamePasswordToken;
import com.lg.cms.entity.SuperUser;
import com.lg.cms.entity.User;
import com.lg.cms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @Description: 普通用户管理实现类
 * @Author: wuyuhang
 * @create: 2020-10-01 12:06
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    public String getName() {
        return "user";
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        //获取用户对象
        SuperUser superUser = (SuperUser) subject.getPrincipal();

        Set<String> roles = new HashSet<String>();
        roles.add("user");
        //创建权限, 角色对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("进入普通用户认证器");
        ShiroUsernamePasswordToken token = (ShiroUsernamePasswordToken)authenticationToken;
        String type = token.getUserType();
        User user = userService.getOne(new QueryWrapper<User>().eq("username", token.getUsername()));
        if(user != null){
            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        }
        return null;
    }
}